
//---------------文章请求部分

/** 
 * type = 1 获取类别
 *  2  获取  key 关键字
*/

const sqls = require('../sqlMap');  //对应的mysql语句
const query = require('../db');
const mysql = require('mysql');
const querystring = require('querystring');
/**    
 *   后 台 文章
 *         getArticle    获取文章标签，获取文章类别
 *     getArticleData   获取文章
 *        postArticle   文章添加
 *      deleteArticle   删除文章
 *
 *      getAritcleTag  //文章标签
 *      deleteArticleTag//删除标签
*/

exports.getArticle=(req,res,next)=>{
    let params = req.query;
    let sql = '';
    switch (params['type']) {
        case '1':
        sql = sqls.findData('zt_category','');
        break;
    case '2':
        sql = sqls.findData('zt_key','');
        break;
        }
        query.connect(sql,function (err,result) {
            console.log(result,556);
        let results={};
        if(err){
                results = { 'ret': 0, 'msg': '获取失败'};
            res.send(results);
        }else {
                results = { 'ret': 1, 'rows': result};
            res.send(results);
        }

    });
}
//------------前后台需要获取文章数据
exports.getArticleData=(req,res,next)=>{
      //type为1 所有，为2单条详细
    //加入數據庫
    let params = req.query;
    if(params['type']==1){
        let sqlParamsEntity = [];
        let page = params['page'];
        let per_page = params['per_page'];
        var startLimit = (page-1)*per_page;
        var limit =`${startLimit},${per_page}`;
        let sql1 = `select a.id,a.key,b.type_name,a.abstr,a.subtitle,a.top,a.create_time,a.title from zt_article a
                    left join zt_category b on a.category_id=b.id
                     limit ${limit};`;
        let sql2 = sqls.countTableLen('zt_article', '');
        let sql3 =`select id,value from zt_key`;
        sqlParamsEntity.push(query.getNewSqlParamEntity(sql1, {}));
        sqlParamsEntity.push(query.getNewSqlParamEntity(sql2, {}));
        sqlParamsEntity.push(query.getNewSqlParamEntity(sql3, {}));
        query.execTrans(sqlParamsEntity, function (err, result) {
            let results = { 'ret': 1, 'rows': result[0], 'total': result[1][0]['len'],'keys': result[2]};
            res.json(results);
        });
    }else{
        let id = params['id'];
        let sqls1 =`select a.id,a.key,a.content,a.abstr,a.create_time,a.title,a.see,b.likes from
                        (select a.id,a.key,a.abstr,h.content,a.create_time,a.title,count(s.see) see from zt_article a
                         left join zt_content h on a.content_id = h.id
                        left join zt_see s on a.id = s.article_id
                        WHERE a.id=${id}
                        group by a.id
                        ) a
                        inner join
                        (select a.id,a.key,a.abstr,h.content,a.create_time,a.title,count(l.like_count) likes from zt_article a
                        left join zt_content h on a.content_id = h.id
                        left join zt_like l on a.id = l.article_id 
                        WHERE a.id=${id}
                        group by a.id) b
                        on a.id = b.id`;
                       query.connect(sqls1,function (err,resultAll) {
                           let results={};
                           if(err){
                               results = { 'ret': 0, 'msg': '获取失败'};
                               res.send(results);
                           }else {
                               results = { 'ret': 1, 'rows': resultAll};
                               res.send(results);
                           }

                       });
                   }

               }
//---------------  文章数据提交------
exports.postArticle=(req,res,next)=>{
    let datas = req.body;
    let unions = '';
    let sqlParamsEntity = [];
     let content = req.body.desc;
    let sqlInsert = sqls.insertTable('zt_content', 'content','?');
    let findLatId = sqls.findLatId('zt_article');
    sqlParamsEntity.push(query.getNewSqlParamEntity(sqlInsert, content));
    sqlParamsEntity.push(query.getNewSqlParamEntity(findLatId, {}));
    query.execTrans(sqlParamsEntity, function (err, result) {
        if (err) {
            results = { 'ret': 0, 'msg': '更新失败'};
            res.send(results);
        } else {
            let eachValue = [];
            let feild = 'content_id,title,subtitle,abstr,category_id,' +
                'imgUrl,`top`,`key`,`status`';
            eachValue.push(result[0]['insertId']); //内容id
            eachValue.push(req.body.title);
            eachValue.push(req.body.abstrTitle); //副标题
            eachValue.push(req.body.abstr);  // 概要
            eachValue.push(req.body.type); //分类
            eachValue.push(req.body.imgSrc); //图片
            eachValue.push(req.body.top); //排序
            eachValue.push(req.body.label);  // 标签
            eachValue.push(req.body.status);  // 状态
            let insetContent = sqls.insertTable('zt_article', feild,'?,?,?,?,?,?,?,?,?');
            let sqls2 = mysql.format(insetContent,eachValue);
            console.log(sqls2,444);
            query.connect(sqls2,function (err,result) {
                let results={};
                if(err){
                    results = { 'ret': 0, 'msg': '更新失败'};
                    res.send(results);
                }else {
                        results = { 'ret': 1};
                    res.send(results);
                }
            });
        }
    });

}


///--------------------文章删除---------
exports.deleteArticle=(req,res,next)=>{
    let params = req.query;
    let sql = sqls.fidDateFromTable('zt_article', params['id'], '', 'content_id');
    query.connect(sql,function (err,result) {
        let results={};
        if(err){
            results = { 'ret': 0, 'msg': '删除失败'};
            res.send(results);
        }else {
            let sql1 = sqls.DeleteData('zt_article', 'id=' + params['id']);
            let sql2 = sqls.DeleteData('zt_content', 'id=' + result[0][0]['content_id']);
            let sqlParamsEntity = [];
            sqlParamsEntity.push(query.getNewSqlParamEntity(sql1, {}));
            sqlParamsEntity.push(query.getNewSqlParamEntity(sql2, {}));
            query.execTrans(sqlParamsEntity, function (err, result1) {
                if (err) {
                    results = { 'ret': 0, 'msg': '删除失败'};
                    res.send(results);
                } else {
                    let results = { 'ret': 1 };
                    res.send(results);
                }
            });
        }

    });
}


/*---------------获取文章类型 tag- zt_category---------------*/
exports.getAritcleTag=(req,res,next)=>{
       let _sql=sqls.findData('zt_category','');
      query.connect(_sql,function (err,result) {
          let results ={};
            if(err){
                results = {ret:0,msg:'获取失败'};
                res.send(results);
            }else{
                results ={ret:1,rows:result};
                res.send(results);
            }
      })

};
/*删除文章标签*/
exports.deleteArticleTag=(req,res,next)=>{
      let _id = req.query.id;
    let where = `??=?`;
     let _sql = sqls.DeleteData('zt_category',where);
         _sql = mysql.format(_sql,['id',_id]);
    console.log(_sql,2333);
    query.connect(_sql,function (err,result) {
        let results ={};
          if(err){
              results = {ret:0,msg:'删除失败'};
              res.send(results);
          }else {
              results ={ret:1};
              res.send(results);
          }
    })
};

/*添加文章标签*/
exports.postArticleTag=(req,res,next)=>{
    let type_name = req.body.type_name;
    let is_unpadate = req.body.is_unpadate;
    let _id = req.body.id;
    let where = `??=?`;
    let _sql='';
    if(is_unpadate){
        let union =`SET type_name=? where id=?`;
         _sql = sqls.update('zt_category',union);
        _sql = mysql.format(_sql,[type_name,_id]);
    }else{
         _sql = sqls.insertTable('zt_category','type_name','?');
        _sql = mysql.format(_sql,[type_name]);
    }
    console.log(_sql);
    query.connect(_sql,function (err,result) {
        let results ={};
        if(err){
            results = {ret:0,msg:'添加失败'};
            res.send(results);
        }else {
            results ={ret:1};
            res.send(results);
        }
    })
}


/*关键字获取*/
exports.getAritcleKey=(req,res,next)=>{
    let _sql=sqls.findData('zt_key','');
    query.connect(_sql,function (err,result) {
        let results ={};
        if(err){
            results = {ret:0,msg:'获取失败'};
            res.send(results);
        }else{
            results ={ret:1,rows:result};
            res.send(results);
        }
    })
};
/*删除key标签*/
exports.deleteArticleKey=(req,res,next)=>{
    let _id = req.query.id;
    let where = `??=?`;
    let _sql = sqls.DeleteData('zt_key',where);
    _sql = mysql.format(_sql,['id',_id]);
    query.connect(_sql,function (err,result) {
        let results ={};
        if(err){
            results = {ret:0,msg:'删除失败'};
            res.send(results);
        }else {
            results ={ret:1};
            res.send(results);
        }
    })
};

/*添加key*/
exports.postArticleKey=(req,res,next)=>{
    let value = req.body.value;
    let is_update = req.body.is_update;
    let _id = req.body.id;
    let where = `??=?`;
    let _sql='';
    if(is_update){
        let union =`SET value=? where id=?`;
        _sql = sqls.update('zt_key',union);
        _sql = mysql.format(_sql,[value,_id]);
    }else{
        _sql = sqls.insertTable('zt_key','value','?');
        _sql = mysql.format(_sql,[value]);
    }
    console.log(_sql);
    query.connect(_sql,function (err,result) {
        let results ={};
        if(err){
            results = {ret:0,msg:'添加失败'};
            res.send(results);
        }else {
            results ={ret:1};
            res.send(results);
        }
    })
}
